import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";
import axios from "axios";
import { GET_ALL_PLACE } from "../../../../constants/api-constants";

const zoomSize = 6;

const getRandomColor = function () {
  return (
    "#" +
    (function get(color): any {
      return (color += "0123456789abcdef"[Math.floor(Math.random() * 16)]) &&
        color.length === 6
        ? color
        : get(color);
    })("")
  );
};

export default () => {
  let barRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let barChart = echarts.init(barRef.current as HTMLDivElement);
    axios.post(GET_ALL_PLACE).then((r) => {
      console.log(r);
      const { mainData } = r.data;
      const datas: any = {};
      mainData.forEach((v: any) => {
        const name = v.application_area.name;
        if (!datas.hasOwnProperty(name)) {
          datas[name] = 0;
        } else {
          datas[name]++;
        }
      });
      console.log(datas);
      const dataAxis: any = [];
      const data: any = [];
      for (let name in datas) {
        if (datas.hasOwnProperty(name)) {
          dataAxis.push(name);
          data.push({
            value: datas[name],
            itemStyle: { color: getRandomColor() },
          });
        }
      }
      const option = {
        title: {
          text: "成果——应用领域",
          textStyle: {
            color: "#235894",
          },
        },
        xAxis: {
          data: dataAxis,
          axisLabel: {
            inside: true,
            textStyle: {
              color: "#fff",
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          z: 10,
        },
        yAxis: {
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            textStyle: {
              color: "#999",
            },
          },
        },
        dataZoom: [
          {
            type: "inside",
          },
        ],
        series: [
          {
            type: "bar",
            showBackground: true,

            data: data,
          },
        ],
      };
      barChart.setOption(option);
      barChart.on("click", function (params) {
        console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
        barChart.dispatchAction({
          type: "dataZoom",
          startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue:
            dataAxis[
              Math.min(params.dataIndex + zoomSize / 2, data.length - 1)
            ],
        });
      });
    });
  });
  return (
    <>
      <div ref={barRef} style={{ width: 400, height: 400 }} />
    </>
  );
};
